﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Model;
using WindowsForms.service;
using WindowsForms.Class;

namespace WindowsForms
{
    public partial class Login : DevExpress.XtraEditors.XtraForm
    {
        private Service1 iQuery;
        public static Staffs STAFF_IDENTITY;
        private Authentication auth;

        public Login()
        {
            iQuery = new Service1();
            this.auth = new Authentication();
            InitializeComponent();
        }

        private bool IsValidCredentials()
        {
            List<Staffs> lstStaffs = new List<Staffs>();
            ConvertToList convert = new ConvertToList();
            lstStaffs = convert.ConvertTolistStaffs(iQuery.SelectLogin(StaffId).Tables[0]);
            STAFF_IDENTITY = lstStaffs[0];
            if (!String.IsNullOrEmpty(STAFF_IDENTITY.Password))
            {
                if (this.auth.VerifyMD5Hashed(txtPw.Text, STAFF_IDENTITY.Password))
                {
                    lock (STAFF_IDENTITY)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        public string StaffId
        {
            get
            {
                return this.txtStaffId.Text;
            }
        }

        public string Password
        {
            get
            {
                return this.txtPw.Text;
            }
        }

        private void txtFrm_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                DialogResult = DialogResult.OK;
                this.Close();
            }
        }

        private void Login_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = !dxValidationProvider1.Validate() && DialogResult == DialogResult.OK;
            if (!e.Cancel && DialogResult == DialogResult.OK)
            {
                if (IsValidCredentials())
                {
                    DialogResult = System.Windows.Forms.DialogResult.OK;
                }
                else
                {
                    e.Cancel = true;
                    this.lblNotFound.Text = "Tài Khoản không tồn tại, Xin hãy nhập Tài Khoản khác";
                }
            }
        }

        private void txtStaffId_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.txtPw.Focus();
            }
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {

        }
    }
}